<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/' }">homepage</el-breadcrumb-item>
    <el-breadcrumb-item>主机管理</el-breadcrumb-item>
  </el-breadcrumb>

  <div>
    <el-table :data="hostTableData" width="80%" ref="hostTableRef">
      <el-table-column prop="id" type="selection" width="55" />
      <el-table-column prop="hostIp" label="主机IP" width="220"></el-table-column>
      <el-table-column prop="account" label="主机帐户" width="220"></el-table-column>
      <el-table-column prop="hostName" label="主机名" width="220"></el-table-column>
      <el-table-column prop="password" label="主机密码"></el-table-column>
      <el-table-column prop="hostPort" label="SSH端口" width="120"></el-table-column>
      <!--<el-table-column width="80">
        <template #default="{ row }">
          <el-icon>
            <EditPen @click="editRow(row)" />
          </el-icon>
        </template>
      </el-table-column>-->
    </el-table>

    <el-dialog v-model="addDialogVisible" ref="hostDialogRef" title="添加主机" width="30%" :before-close="handleClose" :close-on-click-modal="false">
      <el-form ref="formhostRef" :model="formhost" :rules="rules" label-width="120px">
        <el-form-item label="主机IP">
          <el-input v-model="formhost.hostIp"></el-input>
        </el-form-item>
        <el-form-item label="主机名称">
          <el-input v-model="formhost.hostName"></el-input>
        </el-form-item>
        <el-form-item label="主机端口">
          <el-input v-model.number="formhost.hostPort"></el-input>
        </el-form-item>
        <el-form-item label="主机帐户">
          <el-input v-model="formhost.account"></el-input>
        </el-form-item>
        <el-form-item label="主机密码">
          <el-input v-model="formhost.password"></el-input>
        </el-form-item>
      </el-form>

      <div class="dialog-footer">
        <el-button @click="addDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">Save</el-button>
      </div>
    </el-dialog>
  </div>

  <el-menu class="el-menu-demo" mode="horizontal" :ellipsis="false">

    <div class="flex-grow" />
    <el-menu-item index="1" @click="uploadWin(row)">
      <el-icon>
        <UploadFilled />
      </el-icon>Import
    </el-menu-item>
    <el-menu-item index="2" @click="deleteHostRow()">
      <el-icon>
        <DeleteFilled />
      </el-icon>Delete
    </el-menu-item>
    <el-menu-item index="3" @click="editRow()">
      <el-icon>
        <CirclePlusFilled />
      </el-icon>Add
    </el-menu-item>
  </el-menu>

  <el-dialog v-model="uploadDialogVisible" title="Excel Upload" width="30%" :before-close="handleClose" :close-on-click-modal="false">

    <el-upload ref="uploadRef" class="upload-demo" :limit="1" :on-exceed="handleExceed" :auto-upload="false"
      accept=".xlsx,.xls" :file-list="fileList" :on-change="handleChange">
      <template #trigger>
        <el-button type="primary">select file</el-button>
      </template>

      <template #tip>
        <div class="el-upload__tip text-red">
          只能上传excel/xlsx、xls文件,限1个文件，新文件将覆盖旧文件
        </div>
      </template>

      <p v-if="showProgress">上传进度:{{ percent }}</p>

      <el-button class="ml-3" type="success" @click="submitUpload" v-loading="hostLoading">
        upload to server
      </el-button>
    </el-upload>
  </el-dialog>
</template>
 
<script>
import { ref } from 'vue';
import { ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
import axios from 'axios';
import global from '../components/Global.vue';

export default {
  components: {
    ElTable,
    ElTableColumn,
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput
  },
  data() {
    return {
      fileList: [],
      selectedFile: null,
      baseUrl: global.baseUrl,
      listURL: global.baseUrl + "/host/list",
      uploadURL: global.baseUrl + "/host/upload",
      delHostURL: global.baseUrl + "/host/del",
      percent: 0
    }
  },
  created() {
    this.loadHostTableData();
  },
  setup() {
    const hostTableData = ref([
      {
        id: 1,
        hostIp: '192.168.152.100',
        account: 'root',
        hostName: 'hdp10',
        password: 'adsd#@!@#ks231',
        hostPort: 22
      }
    ]);

    const uploadRef = ref({});
    const formhost = ref({
      hostIp: "",
      hostName: "",
      hostPort: "",
      account: "",
      password: ""
    });
    const hostTableRef = ref({});
    //const multipleSelection  = ref({});
    const addDialogVisible = ref(false);
    const uploadDialogVisible = ref(false);

    //const hostLoading = ref({value:false});
    const hostLoading = ref(false);

    let validateIPAddress = (rule, value, callback) => {
      if (value == null) {
        return callback(new Error('IP地址不能为空'));
      }
      let regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/;
      let valdata = value.split(',');
      let isCorrect = true;
      if (valdata.length) {
        for (let i = 0; i < valdata.length; i++) {
          if (regexp.test(valdata[i]) == false) {
            isCorrect = false;
          }
        }
      }
      if (!isCorrect) {
        callback(new Error('请输入正确的IP地址'));
      } else {
        callback()
      }
    }

    const rules = {
      hostIp: [
        { required: true, message: 'Please input host ip', trigger: 'blur', validator: validateIPAddress }
      ],
      hostName: [
        { required: true, message: 'Please input host name', trigger: 'blur' }
      ],
      hostPort: [
        { required: true, message: 'Please input host port', trigger: 'blur' },
        { type: 'number', message: 'host port must be a number', trigger: 'blur' }
      ],
      account: [
        { required: true, message: 'Please input host account', trigger: 'blur' }
      ],
      password: [
        { required: true, message: 'Please input password', trigger: 'blur' }
      ],
    };

    const editRow = () => {
      //this.formhost.value = { ...row };
      addDialogVisible.value = true;
    };

    const uploadWin = (row) => {
      const upload_value = { ...row };
      console.info(upload_value);
      uploadDialogVisible.value = true;
    };

    const submitForm = () => {
      const formRef = formhost;
      console.info(formRef.value);
      
      var url = this.baseUrl + '/host/add';
      console.info("", this.baseUrl, url);
      axios.post(url, formRef.value, global.config)
        .then((response) => {
          /**
          console.info("hostTableData:", hostTableData.value);
          console.info("addDialogVisible:", addDialogVisible); */
          console.log("response.data.data:", response.data);

          hostTableData.value.push(response.data.data);
          addDialogVisible.value = false;

        })
        .catch((error) => {
          console.error(error);
        });
    };

    return {
      hostTableData,
      formhost,
      addDialogVisible,
      uploadDialogVisible,
      rules,
      editRow,
      submitForm,
      uploadWin,
      uploadRef,
      hostTableRef,
      hostLoading
    };
  },
  methods: {
    deleteHostRow() {
      const rows = this.$refs.hostTableRef.getSelectionRows();
      //console.info("global:",this.baseUrl);
      let ids = [];
      rows.forEach(function (element) {
        ids.push(element.id);
      });
      this.$confirm('此操作将永久删除该该机, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var url = this.baseUrl + '/host/dele';
        console.info("======>", this.baseUrl, url);
        axios.request({
          url: url,
          method: "delete",
          headers: global.config,
          data: ids
        }
        ).then(res => {
          console.info("批量删除返回" + res);
          this.$message({
            message: "删除成功",
            type: "success"
          })
          this.hostTableData.forEach((v, i) => {
            //console.info("《 ids 》", ids, "《v》", v, i);
            ids.forEach((vv, ii) => {
              if (vv === v.id) {
                console.info(ii, "< vv , ii >", vv, v.id);
                this.hostTableData.splice(i, 1);
              }
            });
          });
          this.$refs.hostTableRef.clearSelection();
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    },
    loadHostTableData() {
      console.info("", this.listURL);
      axios.get(this.listURL)
        .then((response) => {
          console.log(response.data);
          this.hostTableData = response.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    handleSuccess(response, file, fileList) {
      console.log(response, file, fileList)
      this.$message({
        message: "上传成功:",
        type: "success"
      });
    },
    handleError(err, file, fileList) {
      console.log(err, file, fileList)
      this.$message({
        message: "上传失败",
        type: "error"
      });
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      console.log(this.fileList);
    },
    submitUpload() {
      console.info('>>>>>>>>>>>>>>>>> 开始上传啦!!!');

      let formData = new FormData();
      formData.append("excelFile", this.fileList[0].raw);
      console.log(this.fileList[0].raw);
      this.showProgress = true;
      this.hostLoading = true;
      /**
       this.uploadRef.submit(); 
      */
      let config = {
        headers: { "Content-Type": "multipart/form-data;charset=utf-8" },
        onUploadProgress: ProgressEvent => {
          this.percent = Math.round(ProgressEvent.loaded * 100 / ProgressEvent.total)
        }
      };

      axios.post(this.uploadURL, formData, config)
        .then((response) => {
          this.$message({
            message: "主机上传成功",
            type: "success"
          });
          //console.log(response.data.data);
          this.hostTableData = response.data.data;
          this.showProgress = false;
          this.uploadWin.handleClose;
          this.hostLoading = false;
          this.uploadDialogVisible = false;
        })
        .catch((error) => {
          this.$message({
            message: "主机上传异常:" + error.message,
            type: "success"
          });
          //console.warn("上传失败，异常");
          //console.error(error.message);
          this.showProgress = false;
          this.uploadWin.handleClose;
          this.hostLoading = false;
          this.uploadDialogVisible = false;
        });

    }
  }
};
</script>

<style>
.el-table {
  margin: 3px auto;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-el-table-v2__header-row .custom-header-cell {
  border-right: 1px solid var(--el-border-color);
}

.el-el-table-v2__header-row .custom-header-cell:last-child {
  border-right: none;
}

.el-primary-color {
  background-color: var(--el-color-primary);
  color: var(--el-color-white);
  font-size: 14px;
  font-weight: bold;
}

.el-primary-color .custom-header-cell {
  padding: 0 4px;
}
</style>
  


  